import { el, ro } from "element-plus/es/locales.mjs";
import { defineStore } from "pinia";
import { ref } from "vue";

function initState() {
  return {
    isCollapse: false,
    tags: ref([
      {
        path: '/home',
        name: 'home',
        label: '首页',
        icon: 'home'
      }
    ]),
    currentMenu: null,
    menuList: [],
    token: "",
    routerList: [],
  }
}

export const useAllDataStore = defineStore('allData', () => {
  // ref =state属性
  // computed = getters
  // function =actions
  const state = ref(initState())
  // 面包屑导航联动菜单栏
  function selectMenu(val) {
    if (val.name === "home") {
      state.value.currentMenu = null
    } else {
      let index = state.value.tags.findIndex((item) => item.name === val.name);
      index === -1 ? state.value.tags.push(val) : "";
    }
  }
  // 登录动态路由的设置
  function addMenu(router) {
    const menu = state.value.menuList;
    const module = import.meta.glob("../views/**/*.vue")
    const routeArr = [];
    menu.forEach((item) => {
      if (item.children) {
        item.children.forEach((val) => {
          let url = `../views/${val.url}.vue`
          val.component = module[url]
          routeArr.push(...item.children)
        })
      } else {
        let url = `../views/${item.url}.vue`
        item.component = module[url]
        routeArr.push(item)
      }
    })
    // 解决多账号登录问题
    state.value.routerList = [];
    let routers = router.getRoutes()
    routers.forEach(item => {
      if (item.name == 'main' || item.name == 'login') {
        return
      } else {
        router.removeRote(item.name)
      }

    })
    routeArr.forEach(item => {
      state.value.routerList.push(router.addRoute("main", item))
    })
  }
  // 更新关闭面包屑导航
  function undateTags(tag) {
    let index = state.value.tags.findIndex((item) => item.name === tag.name)
    state.value.tags.splice(index, 1)
  }
  // 更新登录页面的菜单跳转
  function updateMenuList(val) {
    state.value.menuList = val;
  }
  return { state, selectMenu, undateTags, updateMenuList, addMenu, }
})